var selToID = "";
var loginInfo = {};
var teduBoard = null;
// var TRTC = null;
var selSess = null;
var isPushCamera = true;
var enableCamera = true;
var enableMic = true;
var canUndo = "0";
var logType = "2";
var isIMlogin = true;
var synDrawEnable = true;

var isGetMagLogFirst = true;
var isGetMagLog = true;
var msgKey = '';
var logMsgList = [];

var client = null;
var localStream = null;
var remoteStream = null;
var sdkAppId = 0;
var userId = 0;
var userSig = '';
var isSignUp = false;

//判断是否是ios
  var u = navigator.userAgent;
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

//默认好友头像
var friendHeadUrl = 'img/friend.jpg'; //仅demo使用，用于没有设置过头像的好友
//默认群头像
var groupHeadUrl = 'img/group.jpg'; //仅demo使用，用于没有设置过群头像的情况

//设置问诊时间
function setLogTime(time) {
	console.log(isiOS)
  if (!isIMlogin) {
    setTimeout(() => {
      setLogTime(time)
    }, 500);
  } else {
    if (isGetMagLogFirst) {
      isGetMagLogFirst = false;
      if (!isUndefinedAndEmpty(selToID)) {
        lastMsgTime = 0; //第一次拉取好友历史消息时，必须传0
        msgKey = '';
        var logTime = new Date(time).getTime() / 1000;
      }
    }
  }
}

//创建链接
function createClient() {
	var TRTCset = strToJson(sessionStorage.getItem('TRTCset'));
	var roomId = parseInt(TRTCset.room)
	//获取签名
	sdkAppId = TRTCset.appId
	userId = String(TRTCset.userId)
	console.log(userId);
	console.log(typeof userId);
	userSig = TRTCset.sig
	client = TRTC.createClient({
		'mode': 'rtc',
		'sdkAppId':sdkAppId,
		'userId':userId,
		'userSig':userSig
	});
	//注册远程监听，要放在加入房间前--这里用了发布订阅模式
	subscribeStream(client)
	//初始化后才能加入房间
	joinRoom(client, roomId)
}
//加入房间
function joinRoom (client, roomId) {
	console.log('房间号',roomId)
	if (!isSignUp) {
		client.join({ roomId }).catch(error => {
			console.error('进房失败 ' + error);
		}).then(() => {
			isSignUp = true;
			console.log('进房成功');
			//创建本地流
			createStream(userId)
			//播放远端流
			// playStream(client)
		});
	} else {
		Message({
			message: '不能重复加入房间',
			type: 'success'
		});
	}
}
//创建本地音视频流
function createStream (userId) {
	console.log(createStream);
	localStream = TRTC.createStream({ userId, audio: true, video: true, facingMode: 'user' });
	// localStream =localStream 

	localStream.initialize().catch(error => {
		console.error('初始化本地流失败 ' + error);
	}).then(() => {
		console.log('初始化本地流成功');
		// 创建好后才能播放 本地流播放 local_stream 是div的id
		localStream.play('videoDiv1')
		//创建好后才能发布
		publishStream(localStream, client)
	});
}
			
//发布本地音视频流
function publishStream (localStream, client) {
	client.publish(localStream).catch(error => {
		console.error('本地流发布失败 ' + error);
	}).then(() => {
		console.log('本地流发布成功');
	});
}
			
//订阅远端流--加入房间之前
function subscribeStream (Client) {
	Client.on('stream-added', event => {
		remoteStream = event.stream;
		console.log('远端流增加: ' + remoteStream.getId());
		//订阅远端流
		Client.subscribe(remoteStream);
	});
	// 监听用户退出
	Client.on('stream-removed', event => {
		remoteStream = event.stream;
		remoteStream = '';
		console.log('远端流退出',remoteStream,'>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
	});
	//播放远端流
	Client.on('stream-subscribed', event => {
		$('#videoDiv2').html('')		//清空一下，以免重连的时候旧画面div还在
		remoteStream = event.stream;
		console.log('远端流订阅成功：' + remoteStream.getId());
		// 创建远端流标签，因为id是动态的，所以动态创建，用了v-html
		// remoteStream = `<view id="${'remote_stream-' + remoteStream.getId()}"  ></view>`;
		//播放
		remoteStream.play('videoDiv2');
	});
	Client.on('stream-updated', event => {
		remoteStream = event.stream; 
		// 远端流更新事件，用户添加、移除或更换音视频轨道 （ 流取消订阅的时候也会触发 ） 
		// client.unsubscribe(remoteStream)
	})
}
			
//播放远端流
function playStream (client) {
	// 安卓可以,ios不行
	client.on('stream-subscribed', event => {
		remoteStream = event.stream;
		console.log('远端流订阅成功：' + remoteStream.getId());
		// 创建远端流标签，因为id是动态的，所以动态创建，用了v-html
		// remoteStream = `<view id="${'remote_stream-' + remoteStream.getId()}"  ></view>`;
		//播放
		remoteStream.play('videoDiv2');
	});
}
			
//退出音视频
function leaveRoom (client) {
	client.leave().then(() => {
		console.log('退房成功')
		// 停止本地流，关闭本地流内部的音视频播放器
		localStream.stop();
		// 关闭本地流，释放摄像头和麦克风访问权限
		localStream.close();
		// 关闭远端流
		remoteStream = '';
		localStream = null;
		client = null
		isSignUp = false
		// 退房成功，可再次调用client.join重新进房开启新的通话。
	}).catch(error => {
		console.error('退房失败 ' + error);
		// 错误不可恢复，需要刷新页面。
	});
}


// 返回 01-12 的月份值
function getMonth(date) {
  var month = "";
  month = date.getMonth() + 1; // getMonth()得到的月份是0-11
  if (month < 10) {
    month = "0" + month;
  }
  return month;
}
// 返回01-30的日期
function getDay(date) {
  var day = "";
  day = date.getDate();
  if (day < 10) {
    day = "0" + day;
  }
  return day;
}
// 返回小时
function getHours(date) {
  var hours = "";
  hours = date.getHours();
  if (hours < 10) {
    hours = "0" + hours;
  }
  return hours;
}
// 返回分
function getMinutes(date) {
  var minute = "";
  minute = date.getMinutes();
  if (minute < 10) {
    minute = "0" + minute;
  }
  return minute;
}
// 返回秒
function getSeconds(date) {
  var second = "";
  second = date.getSeconds();
  if (second < 10) {
    second = "0" + second;
  }
  return second;
}

